import React, { useEffect, useState } from 'react';
import styles from './index.less';
import { connect } from 'dva';
import { findRoleByUserId } from '@/services/user';
import { PageLoading, TRDefault } from '@/components';
import { useStaticState } from '@/utils';
const RoleFrame = ({ personId, Ltype = '' }) => {
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(false);
  const [url, setUrl] = useState('');
  const ss = useStaticState({
    baseUrl: 'https://finereport.gw-greenenergy.com/webroot/decision/view/form',
    viewlet: 'DIgitalDepartment/SCZX/shaobing/分层目录总览.frm',
  });

  useEffect(() => {
    fetchFn();
  }, []);

  const fetchFn = async () => {
    const res = await findRoleByUserId(personId);
    const roleList = res?.roleList ?? [];
    const roleIds = roleList.map((e) => e?.roleId ?? '');
    if (!personId || !roleIds?.length) {
      return setError(true);
    }
    const params = {
      Ltype,
      viewlet: ss.viewlet,
      Srole: roleIds.join(','), // 角色id
      Suser: personId, // 用户id
    };
    setUrl(`${ss.baseUrl}?${urlParams(params)}`);
    setLoading(false);
  };

  const urlParams = (p) => {
    if (!p) return '';
    let pStr = '';
    for (const k in p) {
      pStr += `&${k}=${p[k]}`;
    }
    return pStr;
  };

  if (loading) return <PageLoading />;
  if (error) return <TRDefault type={'lock'} />;

  return (
    <div className={styles.iframe}>
      <iframe src={url} />
    </div>
  );
};

export default connect(({ user }) => ({
  personId: user.currentUser?.personId,
}))(RoleFrame);
